package com.ist.viewpagerhelper.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.ist.viewpagerhelper.GlideManager;
import com.ist.viewpagerhelper.R;
import com.ist.viewpagerhelper.bean.ViewPagerBean;
import com.ist.viewpagerhelper.indicator.ZoomIndicator;

import java.util.ArrayList;
import java.util.List;

public class BannerViewPagerTail extends ViewPager {
    private static final String TAG = "BannerViewPager";
    private static final int LOOP_MSG = 0x0001;
    private Context mContext;
    private List<View> mViews;
    private boolean isLoop;
    private int mLoopTime;
    private int mCurrentIndex;

    /**
     * handle
     */
    Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == LOOP_MSG){
                mCurrentIndex = getCurrentItem();
                mCurrentIndex ++;
                if (mCurrentIndex == 0){
                    mCurrentIndex = mViews.size() - 2;
                    setCurrentItem(mCurrentIndex,false);
                } else if (mCurrentIndex == (mViews.size() - 1 )){
                    mCurrentIndex = 1;
                    setCurrentItem(mCurrentIndex,false);
                }else{
                    setCurrentItem(mCurrentIndex);
                }

                mHandler.sendEmptyMessageDelayed(LOOP_MSG,mLoopTime);
            }
        }
    };


    public BannerViewPagerTail(Context context) {
        this(context,null);
    }
    public BannerViewPagerTail(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.BannerViewPagerTail);
        isLoop = ta.getBoolean(R.styleable.BannerViewPagerTail_banner_isloop,false);
        mLoopTime = ta.getInteger(R.styleable.BannerViewPagerTail_banner_looptime,2000);
        ta.recycle();

      //  FixedSpeedScroller fixedSpeedScroller = new FixedSpeedScroller(mContext);
      //  fixedSpeedScroller.setViewScrollTime(mContext,this,0);
    }

    public void setViewPagerBean(ViewPagerBean bean){
        if (bean != null){
            setBannerDatas(bean.objects);
            if (bean.bottomLayout != null) {
                ZoomIndicator zoomIndicator = (ZoomIndicator) bean.bottomLayout;
                zoomIndicator.setLoopData(bean);
            }


        }
    }

    /**
     * 配置图片的数据
     * @param datas
     */
    private void setBannerDatas(Object[] datas) {

        mViews = new ArrayList<>();
        for (int i = 0; i < datas.length + 2; i++) {
            ImageView imageView = new ImageView(mContext);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            Object source ;

            if (i == 0){ //第一张的时候，把最后一张填充到第一张的前一张
                source = datas[datas.length - 1];

            }else if (i == datas.length + 1){
                source =  datas[0];
            }else {
                source = datas[i - 1];
            }
            if (source instanceof String){
                new GlideManager.Builder()
                        .setContext(mContext)
                        .setTargetSource((String)source)
                        .setImageView(imageView)
                        .setLoadingBitmap(R.mipmap.ic_launcher)
                        .builder();
                mViews.add(imageView);
            }
            if(source instanceof Integer){
                new GlideManager.Builder()
                        .setContext(mContext)
                        .setTargetSource((Integer) source)
                        .setImageView(imageView)
                        .setLoadingBitmap(R.mipmap.ic_launcher)
                        .builder();
                mViews.add(imageView);
            }

        }
        setAdapter(new CusTomAdapter());
        addOnPageChangeListener(new PageListener());
        setCurrentItem(1);

        if (isLoop){
            mCurrentIndex = 1;
            mHandler.sendEmptyMessageDelayed(LOOP_MSG,mLoopTime);
        }


    }
    class PageListener implements OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_IDLE){
                int currentpageid = getCurrentItem();
                if (currentpageid == 0){
                    setCurrentItem(mViews.size() - 2 ,false);
                } else if (currentpageid == (mViews.size() - 1 )){
                    setCurrentItem(1,false);
                }
                if (isLoop) {
                    mHandler.removeMessages(LOOP_MSG);
                    mHandler.sendEmptyMessageDelayed(LOOP_MSG, mLoopTime);
                }
            }else{
                mHandler.removeMessages(LOOP_MSG);
            }
        }
    }

    class  CusTomAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return mViews.size();
        }
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            //return super.instantiateItem(container, position);
            container.addView(mViews.get(position));
            return mViews.get(position);
        }
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViews.get(position));
        }
    }

    public void onPause(){
        mHandler.removeMessages(LOOP_MSG);
    }
    public void onResume(){
        if (isLoop){
            mHandler.sendEmptyMessageDelayed(LOOP_MSG,mLoopTime);
        }
    }

}